/**
 * Created by xiniu on 2017/8/29.
 */

import React, { Component, PropTypes } from 'react';
import {
    Image,
    StyleSheet,
    Text,
    TextInput,
    View,
    ScrollView,
    NativeModules,
    Modal,
    TouchableOpacity,
    Dimensions,
    Platform,
} from 'react-native';
import Toast from 'react-native-simple-toast';
import CheckBox from 'react-native-checkbox';
import ImagePicker from 'react-native-image-picker';
import Picker from 'react-native-picker';

import SuggestTypeSearchRequest from "../contract/suggest/request/SuggestTypeSearchRequest";
import BusinessImpactSearchRequest from "../contract/suggest/request/BusinessImpactSearchRequest";
import AppService from '../service/AppService';
import MySuggestList from './MySuggestList';
import CoordinationList from './CoordinationList';
import RString from '../language/RString';

const check_Img = require('./img/checked.png');
const uncheck_Img = require('./img/uncheck_Img.png');

export default class Handle extends Component {
    // 初始化
  constructor(props) {
    super(props);
    this.state = {
      title: RString('addSuggest'),
      userId: '',
      userName: '',
      isProject: false,
      pickedType: RString('chooseType'),
      uploadImageUrl: '',
      typeId: '',
      imageList: [],
      imgList: [],
      uploadImageList: [],
      passportId: '',
      suggestId: '',
      showPicker: true,
      modalShow: false,
      filePath: null,
      suggestTypeChildId:'',//提案类型子节点id
      suggestTypeChild: RString('chooseChildType'),//提案类型子节点名称
      businessImpactId:'',//业务影响id
      businessImpactType:RString('businessImpactType'),
      projectTypeId:'',//项目子类型id
      projectType:RString('projectType'),
      projectTypeParentName:'',//项目父类型名称
      projectName:'',//项目名称
      businessImpactName:''//业务名称
    };
  }

  goBack = () => {
    const { navigator } = this.props;
    if (navigator) {
      navigator.pop();
    }
  };
  doClose = () => {
    NativeModules.system.navTo('BACK');
  };

  selectImage() {
    const that = this;
    if (that.state.uploadImageList.length >= 2) {
      that.setState({
        showPicker: false,
      });
    }
    const options = {
        title: RString('chooseHeadImg'),
        storageOptions: {
            skipBackup: true,
            path: 'images',
            waitUntilSaved: true,
        },
        cancelButtonTitle: RString('cancel'),
        takePhotoButtonTitle: RString('takePhoto'),
        chooseFromLibraryButtonTitle: RString('chooseAlbum'),
        quality: 1,
        noData: true,
        maxWidth: 700,
        maxHeight: 700,
    };
    ImagePicker.showImagePicker(options, (response) => {
      if (response.didCancel) {
        console.warn('User cancelled image picker');
      } else if (response.error) {
        console.warn('ImagePicker Error: ', response.error);
      } else if (response.customButton) {
        console.warn('User tapped custom button: ', response.customButton);
      } else {
        const file = {
          uri: '',
          name: 'photo',
          type: 'image/jpeg',
        };
        if (Platform.OS === 'android') {
          file.uri = response.uri;
        } else {
          file.uri = response.uri.replace('file://', '');
        }
        AppService.uploadImage(file, global.passportId).then((response) => {
          const rep = response;
          if (!!rep.url && rep.url.length > 0) {
            AppService.uploadbyfileid({
              fileId: rep.id,
              businessId: that.state.suggestId,
              businessType: 'DOCK',
              businessCategory: 'COMMON',
            }).then((response) => {
              that.state.uploadImageList.push(rep);
              that.setState({
                    imageList: that.state.uploadImageList,
                  });
            });
          }
        });
      }
    });
  }

  isProject() {
    if (this.state.isProject) {
       this.setState({
            isProject: false,
          });
    } else {
       this.setState({
                isProject: true,
              });
    }
  }

  componentWillMount() {
    AppService.getNewId({}).then((response) => {
      this.setState({
        suggestId: response,
      });
    });
    NativeModules.security.getPassportId().then((result) => {
      AppService.getPassport({ id: result }).then((data) => {
        global.tenantId = data.passport.tenantId;
        this.setState({
          userId: data.passport.userId || '',
        });
        this.setState({
          userName: data.passport.userName || '',
        });
      });
    },
        ).catch((error) => {
          console.log(error);
        });
          AppService.searchBusinessImpact({ pageSize: 0, tenantId: global.tenantId,dbType:1,equipmentType:1}).then((data) => {
            for (let i = 0; i < data.result.length; i++) {
              if(data.result[i].parentId !=0){
              }else{
                //项目类型根节点名称
                this.setState({
                   projectTypeParentName: data.result[i].businessImpactName,
                 });

              }
            }
          });
  }
   // 查询提案类型,根节点
       /* 类型选择*/
     selectType() {
      let searchParentSuggestType=new SuggestTypeSearchRequest();
      searchParentSuggestType.setPageSize(0);
       const pickerData = [];
       const selectedValue = [];
       AppService.searchParentSugType(searchParentSuggestType).then((data) => {
         for (let i = 0; i < data.result.length; i++) {
           pickerData.push(data.result[i].suggestTypeName);
         }
         selectedValue.push(data.result[0].suggestTypeName);

         Picker.init({
           pickerData,
           selectedValue,
           pickerConfirmBtnText: RString('confirm'),
           pickerCancelBtnText: RString('cancel'),
           pickerTitleText: RString('chooseType'),
           onPickerConfirm: (pickedType) => {
             this.setState({
               pickedType,
             });
             for (let i = 0; i < data.result.length; i++) {
               if (this.state.pickedType == data.result[i].suggestTypeName) {
                 this.setState({
                   typeId: data.result[i].id,
                   typeName: data.result[i].suggestTypeName,
                 });
               }
             }
           },
         });
         Picker.show();
       });
     }
   // 查询提案类型,子节点，根据父级id获取提案类型子节点
 selectChildType(){
   const pickerData = [];
   const selectedValue = [];
    let searchSuggestType=new SuggestTypeSearchRequest();
        searchSuggestType.setPageSize(0);
        searchSuggestType.setKeyword(this.state.typeId);
   AppService.getSugTypeList(searchSuggestType).then((data) => {
     for (let i = 0; i < data.result.length; i++) {
       pickerData.push(data.result[i].suggestTypeName);
     }
     selectedValue.push(data.result[0].suggestTypeName);

     Picker.init({
       pickerData,
       selectedValue,
       pickerConfirmBtnText: RString('confirm'),
       pickerCancelBtnText: RString('cancel'),
       pickerTitleText: RString('chooseType'),
       onPickerConfirm: (suggestTypeChild) => {
         this.setState({
           suggestTypeChild,
         });
         for (let i = 0; i < data.result.length; i++) {
           if (this.state.suggestTypeChild == data.result[i].suggestTypeName) {
             this.setState({
               suggestTypeChildId: data.result[i].id,
             });
           }
         }
       },
     });
     Picker.show();
   });
 }
// 获取业务影响数据dbType=0
searchBusinessImpact() {
  const pickerData = [];
  const selectedValue = [];
  let businessImpactSearchRequest=new BusinessImpactSearchRequest();
  businessImpactSearchRequest.setPageSize(0);
  businessImpactSearchRequest.setDbType(0);
  AppService.searchBusinessImpact(businessImpactSearchRequest).then((data) => {
    for (let i = 0; i < data.result.length; i++) {
      pickerData.push(data.result[i].businessImpactName);
    }
    selectedValue.push(data.result[0].businessImpactName);

    Picker.init({
      pickerData,
      selectedValue,
      pickerConfirmBtnText: RString('confirm'),
      pickerCancelBtnText: RString('cancel'),
      pickerTitleText: RString('chooseType'),
      onPickerConfirm: (businessImpactType) => {
        this.setState({
          businessImpactType,
        });
        for (let i = 0; i < data.result.length; i++) {
          if (this.state.businessImpactType == data.result[i].businessImpactName) {
            this.setState({
              businessImpactId: data.result[i].id,
              businessImpactName: data.result[i].businessImpactName,
            });
          }
        }
      },
    });
    Picker.show();
  });
}
// 获取项目类型
selectProjectType() {
  const pickerData = [];
  const selectedValue = [];
  AppService.searchBusinessImpact({ pageSize: 0, tenantId: global.tenantId,dbType:1,equipmentType:1 }).then((data) => {
  var result=-1;
    for (let i = 0; i < data.result.length; i++) {
      if(data.result[i].parentId !=0){
        pickerData.push(data.result[i].businessImpactName);
      }else{
        result=i;
      }
    }
    //判断不是父节点名称
    if(result==0){
     selectedValue.push(data.result[1].businessImpactName);
    }else{
     selectedValue.push(data.result[0].businessImpactName);
    }

    Picker.init({
      pickerData,
      selectedValue,
      pickerConfirmBtnText: RString('confirm'),
      pickerCancelBtnText: RString('cancel'),
      pickerTitleText: RString('chooseType'),
      onPickerConfirm: (projectType) => {
        this.setState({
          projectType,
        });
        for (let i = 0; i < data.result.length; i++) {
          if (this.state.projectType == data.result[i].businessImpactName) {
            this.setState({
              projectTypeId: data.result[i].id,
            });
          }
        }
      },
    });
    Picker.show();
  });
}
    // 删除图片
  deleteImg(idx, index) {
    if (this.state.imgList.length <= 3) {
      this.setState({
        showPicker: true,
      });
    }
    const _this = this;
    const vm = {
      businessType: 'DOCK',
      businessId: this.state.suggestId,
    };
        // 获取该提案的图片
    AppService.getUploadImage(vm).then((data) => {
      if (!!data.errors === true && !!data.errors.length > 0) {
        Toast.show(data.errors[0].message);
      } else {
        _this.setState({
          imgList: data.attachmentList,
        });
        for (let i = 0; i < _this.state.imgList.length; i++) {
          if (idx === _this.state.imgList[i].fileId) {
            AppService.deleteUploadImage({ attachmentId: _this.state.imgList[i].id }).then((response) => {
              if (!!response.errors === true && !!response.errors.length > 0) {
                Toast.show(response.errors[0].message);
              } else {
                _this.state.uploadImageList.splice(index, 1);
                _this.setState({
                    imageList: _this.state.uploadImageList,
                  });
              }
            });
          }
        }
      }
    });
  }

  enlargeImg(url) {
    this.setState({
      modalShow: true,
      filePath: url,
    });
  }

  closeModal() {
    this.setState({
      modalShow: false,
    });
  }

    // 渲染图片
  renderImage = (v, i) => (
    <View style={{ position: 'relative' }} key={i}>
      <TouchableOpacity onPress={() => this.deleteImg(v.id, i)} style={styles.deleteImage}>
        <Image source={require('./img/chahao.png')} style={{ width: 10, height: 10 }} />
      </TouchableOpacity>
      <TouchableOpacity onPress={() => this.enlargeImg(v.url)}>
        <Image style={styles.uploadImg} source={{ uri: v.url }} />
      </TouchableOpacity>
    </View>
        );

    // 非空校验
  checkSuggest = (suggest) => {
    if (suggest != null) {
      if (suggest.suggestTitle == null || suggest.suggestTitle.trim() == '') {
        Toast.show(RString('input_title'));
        return false;
      } else if (suggest.suggestContent == null || suggest.suggestContent.trim() == '') {
        Toast.show(RString('input_detail'));
        return false;
      } else if (suggest.suggestTypeId == 0) {
        Toast.show(RString('choose_type'));
        return false;
      }else if (suggest.suggestTypeChildId == 0) {
           Toast.show(RString('choose_child_type'));
           return false;
      }else if (suggest.businessImpactId == 0) {
          Toast.show(RString('choose_business_type'));
          return false;
       }else if (suggest.projectTypeId == 0) {
           if(suggest.isProject==true){
            Toast.show(RString('choose_project_type'));
              return false;
           }
       }
      return true;
    }
    Toast.show(RString('input_info'));
    return false;
  };

  cancelEdit = () => {
    const { navigator } = this.props;
    if (navigator) {
      navigator.pop();
    }
  };

    // 保存
  save = () => {
    const vm = {
      id: this.state.suggestId,
      tenantId: global.tenantId,
      suggestTitle: this.state.suggestTitle,
      suggestContent: this.state.suggestContent,
      suggestPersonId: this.state.userId,
      isProject: this.state.isProject,
      suggestType: this.state.typeName,
      suggestTypeId: this.state.typeId,
      suggestTypeChildId: this.state.suggestTypeChildId,
      businessImpactId: this.state.businessImpactId,
      projectTypeId: this.state.projectTypeId,
      status:"TO_ACCEPT",
    };
    if (this.checkSuggest(vm)) {
      const _this = this;
      if (vm.suggestTitle && vm.suggestTitle.length > 12) {
        Toast.show(RString('max_title'));
      } else {
        AppService.apiSuggestCreate(vm).then((data) => {
          if (!!data.errors === true && !!data.errors.length > 0) {
            Toast.show(data.errors[0].message);
          } else {
            Toast.show(RString('success_create'));
            setTimeout(function () {
              const { navigator } = _this.props;
              if (navigator) {
                if (global.isCoordinator) {
                  navigator.push({
                      name: 'Add',
                      component: Add,
                    });
                } else {
                  navigator.push({
                      name: 'MySuggestList',
                      component: MySuggestList,
                    });
                }
              }
            }, 2000);
          }
        });
      }
    }
  };


  render() {
    return (
      <View style={{ position: 'relative', flex: 1 }}>
        <Modal
          animationType="slide"
          transparent
          visible={this.state.modalShow}
          onShow={() => {}}
          onRequestClose={() => {}}
        >
          <TouchableOpacity activeOpacity={1} style={styles.modalLayout} onPress={() => { this.closeModal(); }}>
            <Image style={styles.modalView} source={{ uri: `${this.state.filePath}?x-oss-process=image/resize,m_lfit,w_640,h_640` }} resizeMode="contain" />
          </TouchableOpacity>
        </Modal>
        <View style={styles.commonHeader}>
          <TouchableOpacity onPress={this.goBack.bind(this)} style={styles.back}>
            <Image source={require('./img/leftArrow.png')} />
          </TouchableOpacity>
          <TouchableOpacity onPress={this.doClose.bind(this)} style={styles.toIndex}>
            <Image source={require('./img/chahao.png')} />
          </TouchableOpacity>
          <View style={{ justifyContent: 'center' }}>
            <Text style={{ color: '#fff', fontSize: 16 }}>{this.state.title}</Text>
          </View>
        </View>
        <ScrollView style={styles.wrap}>
          <View style={styles.detailWrap}>
            <View style={styles.detailTop}>
              <View style={styles.imgWrap}>
                <Image style={styles.themeImg} source={require('./img/theme.png')} />
              </View>
              <View style={{ flex: 7 }}>
                <TextInput
                  style={{ fontSize: 16 }}
                  placeholder={RString('title')}
                  underlineColorAndroid="transparent"
                  placeholderTextColor="#A9A9A9"
                  onChangeText={text => this.setState({ suggestTitle: text })}
                />
              </View>
            </View>
            <View style={styles.detail}>
              <View style={styles.imgWrap}>
                <Image style={styles.themeImg} source={require('./img/record.png')} />
              </View>
              <View style={[styles.wordWrap, { paddingTop: 0, paddingBottom: 0, height: 100 }]}>
                <TextInput
                  style={{ flex: 1, fontSize: 16 }}
                  placeholder={RString('suggestDetail')}
                  underlineColorAndroid="transparent"
                  placeholderTextColor="#A9A9A9"
                  multiline
                  numberOfLines={4}
                  textAlignVertical="top"
                  onChangeText={text => this.setState({ suggestContent: text })}
                />
              </View>
            </View>
            <View style={styles.detail}>
              <View style={styles.imgWrap}>
                <Image style={styles.themeImg} source={require('./img/person.png')} />
              </View>
              <View style={styles.wordWrap}>
                <View style={{ flex: 1 }}>
                  <Text style={styles.detailFont} numberOfLines={1}>{this.state.userName}</Text>
                </View>
              </View>
            </View>
            <View style={styles.detail}>
              <View style={styles.imgWrap}>
                <Image style={styles.themeImg} source={require('./img/floor.png')} />
              </View>
              <TouchableOpacity style={styles.wordWrap} onPress={this.selectType.bind(this)}>
                <Text style={{ fontSize: 16, color: '#000' }} numberOfLines={1}>{this.state.pickedType}</Text>
              </TouchableOpacity>
            </View>
            <View style={styles.detail}>
            <View style={styles.imgWrap}>
                <Image style={styles.themeImg} source={require('./img/suggestTypeChild.png')} />
              </View>
              <TouchableOpacity style={styles.wordWrap}  onPress={this.selectChildType.bind(this)}>
                <Text style={{ fontSize: 16, color: '#000' }} numberOfLines={1}>{this.state.suggestTypeChild}</Text>
             </TouchableOpacity>
           </View>
             <View style={styles.detail}>
              <View style={styles.imgWrap}>
               <Image style={styles.themeImg} source={require('./img/businessImpact.png')} />
             </View>
             <TouchableOpacity style={styles.wordWrap} onPress={this.searchBusinessImpact.bind(this)}>
               <Text style={{ fontSize: 16, color: '#000' }} numberOfLines={1}>{this.state.businessImpactType}</Text>
               </TouchableOpacity>
             </View>
            <View style={styles.detail}>
              <View style={styles.imgWrap}>
                <Image style={styles.themeImg} source={require('./img/image.png')} />
              </View>
              <View style={[styles.wordWrap, { flexWrap: 'wrap', paddingLeft: 5, paddingBottom: 5 }]}>
                {this.state.imageList.map((v, i) => this.renderImage(v, i))}
                {this.state.showPicker && <TouchableOpacity onPress={() => { this.selectImage(); }}>
                  <Image style={styles.uploadImg} source={require('./img/addImage.png')} />
                </TouchableOpacity>}
              </View>
            </View>
            <View style={styles.detail}>
              <View style={styles.imgWrap}>
                <Image style={styles.themeImg} source={require('./img/project.png')} />
              </View>
              <View style={styles.lastWordWrap}>
                <Text style={styles.detailFont}>{this.state.projectTypeParentName}</Text>
                <View style={styles.itemIcon}>
                  <CheckBox label="" underlayColor="#fff" uncheckedImage={uncheck_Img} checkedImage={check_Img} onChange={() => this.isProject()} />
                </View>
              </View>
            </View>
          </View>
                {this.state.isProject == false ? (
                null) : (
                <View style={styles.detail}>
                 <View style={styles.imgWrap}>
                      <Image style={styles.themeImg} source={require('./img/projectType.png')} />
                    </View>
                    <TouchableOpacity style={styles.wordWrap} onPress={this.selectProjectType.bind(this)}>
                      <Text style={{ fontSize: 16, color: '#000' }} numberOfLines={1}>{this.state.projectType}</Text>
                      </TouchableOpacity>
                 </View>
            )}
          <View style={styles.buttonWrap}>
            <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'flex-start' }}>
              <TouchableOpacity style={styles.editBtn} onPress={this.cancelEdit.bind(this)}>
                <Text style={{ color: '#424242' }}>{RString('cancel')}</Text>
              </TouchableOpacity>
            </View>
            <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'flex-end' }}>
              <TouchableOpacity style={styles.distributeBtn} onPress={() => { this.save(); }}>
                <Text style={{ color: '#fff' }}>{RString('submit')}</Text>
              </TouchableOpacity>
            </View>
          </View>
        </ScrollView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  modalLayout: {
    width: Dimensions.get('window').width,
    height: Dimensions.get('window').height,
    backgroundColor: 'rgba(0,0,0,.8)',
  },
  modalView: {
    width: Dimensions.get('window').width,
    height: Dimensions.get('window').height,
  },
  wrap: {
    backgroundColor: '#fff',
  },
  commonHeader: {
    height: Platform.OS === 'android' ? 50 : 60,
    paddingTop: Platform.OS === 'ios' ? 20 : 0,
    backgroundColor: '#333238',
    flexDirection: 'row',
    justifyContent: 'center',
    position: 'relative',
  },
  back: {
    width: 30,
    position: 'absolute',
    left: 20,
    top: 0,
    height: Platform.OS === 'android' ? 50 : 60,
    paddingTop: Platform.OS === 'ios' ? 20 : 0,
    justifyContent: 'center',
  },
  toIndex: {
    width: 30,
    position: 'absolute',
    left: 70,
    top: 0,
    height: Platform.OS === 'android' ? 50 : 60,
    paddingTop: Platform.OS === 'ios' ? 20 : 0,
    justifyContent: 'center',
  },
  detailWrap: {
    flex: 1,
    paddingLeft: 10,
    paddingRight: 10,
    backgroundColor: '#fff',
  },
  detail: {
    paddingLeft: 10,
    paddingRight: 6,
    flexDirection: 'row',
  },
  detailTop: {
    paddingTop: Platform.OS === 'ios' ? 15 : 0,
    paddingBottom: Platform.OS === 'ios' ? 15 : 0,
    paddingLeft: 10,
    paddingRight: 6,
    borderBottomWidth: 1,
    borderStyle: 'solid',
    borderBottomColor: '#eee',
    flexDirection: 'row',
  },
  imgWrap: {
    flex: 1,
    justifyContent: 'center',
  },
  themeImg: {
    width: 16,
    height: 16,
  },
  wordWrap: {
    flex: 7,
    borderBottomWidth: 1,
    borderStyle: 'solid',
    borderBottomColor: '#eee',
    paddingTop: 15,
    paddingBottom: 15,
    flexDirection: 'row',
  },
  lastWordWrap: {
    flex: 7,
    paddingTop: 15,
    paddingBottom: 15,
    flexDirection: 'row',
  },
  detailFont: {
    fontSize: 16,
    color: '#000',
    flex: 1,
  },
  detailFontBold: {
    fontWeight: 'bold',
    fontSize: 16,
    color: '#000',
  },
  detailTime: {
    fontSize: 14,
    color: '#999',
  },
  uploadImg: {
    width: 80,
    height: 80,
    marginRight: 10,
    marginBottom: 10,
  },
  comment: {
    flex: 1,
    height: 25,
    paddingLeft: 20,
    paddingRight: 20,
    backgroundColor: '#ECECF1',
    justifyContent: 'center',
  },
  commentWrap: {
    flex: 1,
    paddingLeft: 20,
    paddingRight: 20,
    paddingTop: 20,
  },
  commentDetail: {
    flexDirection: 'row',
    marginBottom: 30,
  },
  commentAvatar: {
    width: 40,
    height: 40,
    marginRight: 15,
  },
  buttonWrap: {
    flex: 1,
    height: 55,
    paddingLeft: 20,
    paddingRight: 20,
    paddingTop: 10,
    paddingBottom: 10,
    flexDirection: 'row',
  },
  editBtn: {
    width: 100,
    borderWidth: 0.5,
    borderStyle: 'solid',
    borderColor: '#333',
    borderRadius: 5,
    paddingTop: 8,
    paddingBottom: 8,
    flexDirection: 'row',
    justifyContent: 'center',
  },
  distributeBtn: {
    width: 100,
    borderRadius: 5,
    paddingTop: 8,
    paddingBottom: 8,
    backgroundColor: '#3399FF',
    flexDirection: 'row',
    justifyContent: 'center',
  },
  deleteImage: {
    width: 20,
    height: 20,
    position: 'absolute',
    top: 0,
    right: 10,
    zIndex: 2,
    backgroundColor: 'rgba(0,0,0,.7)',
    paddingLeft: 5,
    paddingRight: 5,
    justifyContent: 'center',
  },
});
